<template>
  <div>
    <t-card class="list-card-container" :bordered="false">
      <t-row justify="space-between">
        <div class="left-operation-container">
          <t-button @click="formDialogVisible = true">新建线索</t-button>
        </div>
        <div class="search-input">
          <t-button theme="default" @click="refreshTable">刷新</t-button>
        </div>
      </t-row>

      <dialog-form v-model:visible="formDialogVisible" :data="formData" @refresh-table="refreshTable" />

      <t-table
        :data="data"
        :columns="columns"
        :row-key="rowKey"
        vertical-align="top"
        :hover="true"
        :pagination="pagination"
        :loading="dataLoading"
        :header-affixed-top="headerAffixedTop"
        @page-change="rehandlePageChange"
      >
        <template #projectBusinessLicenseImages="{ row }">
          <template v-if="row.projectBusinessLicenseImages && row.projectBusinessLicenseImages.length > 0">
            <t-image-viewer
              :images="row.projectBusinessLicenseImages.map((o:any) => `${o.filePath}`)"
            >
              <template #trigger="{ open }">
                <t-space>
                  <t-link theme="primary" @click="open">查看</t-link>
                  <t-popconfirm
                    content="确认删除吗"
                    theme="danger"
                    @confirm="
                      () => {
                        post('/aliyun/attachmentRemove', {
                          attachmentIds: row.projectBusinessLicenseImages.map((o: any) => o.fileId),
                        }).then((res) => {
                          refreshTable();
                        });
                      }
                    "
                  >
                    <t-link theme="danger">删除</t-link>
                  </t-popconfirm>
                </t-space>
              </template>
            </t-image-viewer>
          </template>
          <template v-else>
            <t-upload :multiple="false" accept="image/*" :request-method="(files) => updateMethod(row, files)">
              <t-link theme="primary">上传</t-link>
            </t-upload>
          </template>
        </template>
        <template #projectCorporationImages="{ row }">
          <template v-if="row.projectCorporationImages && row.projectCorporationImages.length > 0">
            <t-image-viewer
              :images="row.projectCorporationImages.map((o:any) => `${o.filePath}`)"
            >
              <template #trigger="{ open }">
                <t-space>
                  <t-link theme="primary" @click="open">查看</t-link>
                  <!--                  <t-popconfirm-->
                  <!--                    content="确认删除吗"-->
                  <!--                    theme="danger"-->
                  <!--                    @confirm="-->
                  <!--                      () => {-->
                  <!--                        post('/aliyun/attachmentRemove', {-->
                  <!--                          attachmentIds: row.projectBusinessLicenseImages.map((o: any) => o.fileId),-->
                  <!--                        }).then((res) => {-->
                  <!--                          refreshTable();-->
                  <!--                        });-->
                  <!--                      }-->
                  <!--                    "-->
                  <!--                  >-->
                  <!--                    <t-link theme="danger">删除</t-link>-->
                  <!--                  </t-popconfirm>-->
                </t-space>
              </template>
            </t-image-viewer>
          </template>
        </template>
        <template #projectPublishTime="{ row }">
          <template v-if="row.projectPublishTime">
            {{ `${dayjs(row.projectPublishTime).format('YYYY-MM-DD HH:mm:ss')}(${row.projectPublishUserName})` }}
          </template>
        </template>
        <template #projectFoundingTime="{ row }">
          <template v-if="row.projectFoundingTime">
            {{ `${dayjs(row.projectFoundingTime).format('YYYY-MM-DD')}` }}
          </template>
        </template>
        <template #createTime="{ row }">
          {{ `${dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss')}(${row.createUserName})` }}
        </template>
        <template #updateTime="{ row }">
          <template v-if="row.updateTime">
            {{ `${dayjs(row.updateTime).format('YYYY-MM-DD HH:mm:ss')}(${row.updateUserName})` }}
          </template>
        </template>
        <template #op="slotProps">
          <t-space>
            <t-link theme="primary" @click="handleClickDetail(slotProps)">编辑</t-link>
            <t-link theme="danger" @click="handleClickDelete(slotProps)">删除</t-link>
            <template v-if="slotProps.row.projectStatusValue !== 4">
              <t-popconfirm
                theme="warning"
                content="确认上架该线索？"
                @confirm="
                  () => {
                    post('/project/putaway', { projectId: slotProps.row.projectId }).then((res) => {
                      refreshTable();
                    });
                  }
                "
              >
                <t-link theme="primary">上架</t-link>
              </t-popconfirm>
            </template>
            <template v-if="slotProps.row.projectStatusValue === 4">
              <t-popconfirm
                theme="warning"
                content="确认下架该线索？"
                @confirm="
                  () => {
                    post('/project/delist', { projectId: slotProps.row.projectId }).then((res) => {
                      refreshTable();
                    });
                  }
                "
              >
                <t-link theme="primary">下架</t-link>
              </t-popconfirm>
            </template>
          </t-space>
        </template>
      </t-table>
    </t-card>

    <t-dialog
      v-model:visible="confirmVisible"
      header="确认删除当前所选系统配置？"
      :body="confirmBody"
      :on-cancel="onCancel"
      @confirm="onConfirmDelete"
    />
  </div>
</template>

<script lang="tsx">
export default {
  name: 'ProjectList',
};
</script>

<script setup lang="tsx">
// @ts-ignore
import OSS from 'ali-oss';
import dayjs from 'dayjs';
import { MessagePlugin, PrimaryTableCol, RequestMethodResponse } from 'tdesign-vue-next';
import { computed, onMounted, ref } from 'vue';

import { post } from '@/api/common';
import { loadTableList } from '@/api/list';
import { prefix } from '@/config/global';
import { useSettingStore } from '@/store';

import type { FormData } from './components/DialogForm.vue';
import DialogForm from './components/DialogForm.vue';

const store = useSettingStore();

const updateMethod = (data: any, file: any) => {
  console.log('data', data, 'file', file);
  return new Promise<RequestMethodResponse>((resolve) => {
    post('/aliyun/ststoken/get', {}).then((res) => {
      console.log('res', res);
      const alioss = new OSS({
        region: res.region,
        accessKeyId: res.accessKeyId,
        accessKeySecret: res.accessKeySecret,
        stsToken: res.securityToken,
        bucket: res.bucket,
      });
      const filePath = `projectBusinessLicense/${dayjs().format('YYYY/MM/DD')}/${crypto.randomUUID().replace('-', '') + file.name.substring(file.name.indexOf('.'))}`;
      console.log('filepath', filePath);
      alioss.put(filePath, file.raw).then((res: any) => {
        console.log('res', res);
        post('/aliyun/attachmentUpload', {
          filePath,
          objType: 0,
          objId: data.projectId,
          fileSuffix: file.name.substring(file.name.indexOf('.') + 1),
          fileSize: file.size,
          originalFileName: file.name,
          fileType: file.type,
        }).then((res: any) => {
          console.log('res', res);
          refreshTable();
        });
        // resolve({ status: 'success', response: { url: 'https://tdesign.gtimg.com/site/avatar.jpg' } });
        resolve({ status: 'success', response: { url: `https://file.fanshilz.com/${file.name}` } });
      });
    });
  });
};

const columns: PrimaryTableCol[] = [
  { title: '线索ID', colKey: 'projectId' },
  { title: '编号', colKey: 'projectUuid' },
  { title: '名称', colKey: 'projectName' },
  { title: '简称', colKey: 'projectShortName' },
  { title: '营业执照', colKey: 'projectBusinessLicenseImages' },
  { title: '公司照片', colKey: 'projectCorporationImages' },
  { title: '年收入(万元)', colKey: 'projectIncomeYearMoney' },
  { title: '年利润(万元)', colKey: 'projectProfitYearMoney' },
  { title: '售价(万元)', colKey: 'projectSellingPriceMoney' },
  { title: '成立时间', colKey: 'projectFoundingTime' },
  { title: '成立年数', colKey: 'projectFoundingTimeYear' },
  { title: '省份', colKey: 'projectProvinceName' },
  { title: '城市', colKey: 'projectCityName' },
  { title: '区域', colKey: 'projectAreaName' },
  { title: '行业', colKey: 'projectIndustryLabel' },
  { title: '类型', colKey: 'projectTypeLabel' },
  { title: '员工人数', colKey: 'projectEmployeesNumber' },
  { title: '出售原因', colKey: 'projectSellReasonLabel' },
  { title: '出售股份比例', colKey: 'projectSellSharesProportion' },
  { title: '状态', colKey: 'projectStatusLabel' },
  // { title: '交易状态', colKey: 'projectTradingStatusLabel' },
  { title: '排序', colKey: 'projectSort' },
  { title: '发布时间', colKey: 'projectPublishTime' },
  { title: '身份', colKey: 'projectUserTypeLabel' },
  { title: '用户', colKey: 'projectUserName' },
  { title: '用户电话', colKey: 'projectUserMobile' },
  { title: '用户年龄', colKey: 'projectUserAge' },
  // { title: '微信用户', colKey: 'projectWechatUserNickName' },
  // { title: '微信用户电话', colKey: 'projectWechatUserMobile' },
  { title: '公司介绍', colKey: 'projectCorporationDesc' },
  { title: '生意亮点', colKey: 'projectBusinessHighlightDesc' },
  { title: '运营情况', colKey: 'projectOperationSituationDesc' },
  { title: '其他信息', colKey: 'projectOtherDesc' },
  { title: '创建', colKey: 'createTime' },
  { title: '更新', colKey: 'updateTime' },
  { title: '操作', colKey: 'op' },
];

const INITIAL_DATA: FormData = {
  projectId: null,
  projectUuid: '',
  projectName: '',
  projectShortName: '',
  projectIncomeYearMoney: 0,
  projectProfitYearMoney: 0,
  projectFoundingTime: '',
  projectFoundingTimeYear: 0,
  projectProvinceName: '',
  projectProvinceCode: '',
  projectCityName: '',
  projectCityCode: '',
  projectAreaName: '',
  projectAreaCode: '',
  projectSellingPriceMoney: 0,
  projectIndustryLabel: '',
  projectIndustryValue: 0,
  projectTypeLabel: '',
  projectTypeValue: 0,
  projectEmployeesNumber: 0,
  projectSellReasonLabel: '',
  projectSellReasonValue: 0,
  projectSellSharesProportion: 0,
  projectCorporationDesc: '',
  projectBusinessHighlightDesc: '',
  projectOperationSituationDesc: '',
  projectOtherDesc: '',
  projectStatusLabel: '',
  projectStatusValue: 0,
  // projectTradingStatusLabel: '',
  // projectTradingStatusValue: 0,
  projectUserName: '',
  projectUserMobile: '',
  projectUserAge: null,
  projectUserTypeLabel: '',
  projectUserTypeValue: null,
  // projectWechatUserNickName: '',
  // projectWechatUserMobile: '',
  projectSort: null,
};

const formData = ref({ ...INITIAL_DATA });

const formDialogVisible = ref(false);

const data = ref([]);
const pagination = ref({
  defaultPageSize: 20,
  total: -1,
  defaultCurrent: 1,
});

// const searchValue = ref('');

const dataLoading = ref(false);

const refreshTable = async () => {
  pagination.value.total = -1;
  await fetchData();
};

const fetchData = async () => {
  dataLoading.value = true;
  try {
    const { list, total } = await loadTableList('/project/table', {
      // @ts-ignore
      current: pagination.value.current || pagination.value.defaultCurrent,
      // @ts-ignore
      pageSize: pagination.value.pageSize || pagination.value.defaultPageSize,
      total: pagination.value.total,
    });
    data.value = list;
    pagination.value = {
      ...pagination.value,
      total,
    };
  } catch (e) {
    console.log(e);
  } finally {
    dataLoading.value = false;
  }
};

const deleteIdx = ref(-1);
const confirmBody = computed(() => {
  if (deleteIdx.value > -1) {
    const { projectName } = data.value[deleteIdx.value];
    return `删除后， ${projectName} 的所有配置将被清空，且无法恢复`;
  }
  return '';
});

onMounted(() => {
  fetchData();
});

const confirmVisible = ref(false);

const resetIdx = () => {
  deleteIdx.value = -1;
};

const onConfirmDelete = async () => {
  // 真实业务请发起请求
  await post(`/project/remove/${data.value[deleteIdx.value].configId}`, {});
  //
  data.value.splice(deleteIdx.value, 1);
  pagination.value.total = data.value.length;
  confirmVisible.value = false;
  MessagePlugin.success('删除成功');
  resetIdx();
  await refreshTable();
};

const onCancel = () => {
  resetIdx();
};

const rowKey = 'projectId';

const rehandlePageChange = (curr: unknown, pageInfo: unknown) => {
  console.log('分页变化', curr, pageInfo);
  // @ts-ignore
  pagination.value.current = curr.current;
  // @ts-ignore
  pagination.value.pageSize = curr.pageSize;
  fetchData();
};

const handleClickDetail = (data: any) => {
  // router.push('/detail/base');
  console.log(`row`, data.row);
  formData.value = { ...data.row };
  formDialogVisible.value = true;
};

const handleClickDelete = (row: { rowIndex: any }) => {
  deleteIdx.value = row.rowIndex;
  confirmVisible.value = true;
};

const headerAffixedTop = computed(
  () =>
    ({
      offsetTop: store.isUseTabsRouter ? 48 : 0,
      container: `.${prefix}-layout`,
    }) as any,
);
</script>

<style lang="less" scoped>
.payment-col {
  display: flex;

  .trend-container {
    display: flex;
    align-items: center;
    margin-left: var(--td-comp-margin-s);
  }
}

.list-card-container {
  padding: var(--td-comp-paddingTB-xxl) var(--td-comp-paddingLR-xxl);

  :deep(.t-card__body) {
    padding: 0;
  }
}

.left-operation-container {
  display: flex;
  align-items: center;
  margin-bottom: var(--td-comp-margin-xxl);

  .selected-count {
    display: inline-block;
    margin-left: var(--td-comp-margin-l);
    color: var(--td-text-color-secondary);
  }
}

.search-input {
  //width: 360px;
}
</style>
